import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { toast } from '@/hooks/use-toast';
import { invoke } from '@tauri-apps/api/core';
import { BzUser } from '@/lib/models';
import { z } from 'zod';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormMessage,
} from '@/components/ui/form';
import { LoadingSpinner } from './ui/loading-spinner';
import { useState } from 'react';

interface LoginPageProps {
  onLogIn: (user: BzUser) => void;
}

const formScheme = z.object({
  username: z
    .string()
    .min(2, { message: '请输入账号' })
    .max(50, { message: '账户名过长' }),
  password: z
    .string()
    .min(2, { message: '请输入密码' })
    .max(50, { message: '密码过长' }),
});

export default function LoginPage({ onLogIn }: LoginPageProps) {
  const [isLoading, setIsLoading] = useState(false);

  const form = useForm<z.infer<typeof formScheme>>({
    resolver: zodResolver(formScheme),
    defaultValues: {
      username: '',
      password: '',
    },
  });

  async function onSubmit({ username, password }: z.infer<typeof formScheme>) {
    try {
      setIsLoading(true);
      const user = await invoke<BzUser>('bz_login', { username, password });
      if (!!user) {
        toast({ title: '登录成功' });
        onLogIn(user);
      } else {
        toast({ title: '登录失败' });
      }
    } catch (err) {
      console.log('err:', err);
      toast({ title: err as string });
    } finally {
      setIsLoading(false);
    }
  }

  return (
    <div className='grid min-h-screen w-full grid-cols-1 lg:grid-cols-2'>
      <div className='hidden bg-gray-100 lg:block dark:bg-gray-800'>
        {/* <img */}
        {/*   src="/login.svg" */}
        {/*   alt="Login Illustration" */}
        {/*   width={1920} */}
        {/*   height={1080} */}
        {/*   className="h-full w-full object-cover" */}
        {/*   style={{ aspectRatio: "1920/1080", objectFit: "cover" }} */}
        {/* /> */}
      </div>
      <div className='flex items-center justify-center p-6 lg:p-10'>
        <div className='mx-auto w-full max-w-[400px] space-y-6'>
          <div className='space-y-2 text-center'>
            <h1 className='text-3xl font-bold'>欢迎使用</h1>
            <p className='text-gray-500 dark:text-gray-400'>
              请输入账号密码登录
            </p>
          </div>
          <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className='space-y-4'>
              <FormField
                control={form.control}
                name='username'
                render={({ field }) => (
                  <FormItem>
                    <Label>账号</Label>
                    <FormControl>
                      <Input {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name='password'
                render={({ field }) => (
                  <FormItem>
                    <Label>密码</Label>
                    <FormControl>
                      <Input type='password' {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <Button disabled={isLoading} type='submit' className='w-full'>
                {isLoading && <LoadingSpinner />}
                登录
              </Button>
            </form>
          </Form>
        </div>
      </div>
    </div>
  );
}
